package zhh.tangbao.system.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 2023/2/27
 *
 * @author 粥灰灰
 * @version 1.0
 * 描述
 */

@Slf4j
@Component
public class HttpClientUtil {

    @Autowired
    private PoolingHttpClientConnectionManager manager;

    /**
     * 传统Get请求方式
     * 在已知返回内容结构的情况下直接转换成对象
     *
     * @param url            需要自行拼装query参数
     * @param responseStruct 请求的响应结构
     * @param <T>
     * @return
     */
    public <T> T doGet(String url, Class<T> responseStruct) {
        return JSONObject.parseObject(doGet(url), responseStruct);
    }

    public String doGet(String url) {
        try {
            CloseableHttpClient client = getClient(manager);
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse execute = client.execute(httpGet);
            return EntityUtils.toString(execute.getEntity(), StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("HttpClientUtil.doGet(String url): {}", e.getMessage());
            return null;
        }
    }

    public String doPost(String url, String body) {
        try {
            CloseableHttpClient client = getClient(manager);
            HttpPost post = new HttpPost(url);
            StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8);
            post.setEntity(entity);
            CloseableHttpResponse execute = client.execute(post);
            return EntityUtils.toString(execute.getEntity(), StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("HttpClientUtil.doPost(String url, String body): {}", e.getMessage());
            return null;
        }
    }

    public <T> T doPost(String url, String body, Class<T> responseStruct) {
        String s = doPost(url, body);
        return JSONObject.parseObject(s, responseStruct);
    }

    private static CloseableHttpClient getClient(PoolingHttpClientConnectionManager manager) {
        return HttpClients.custom().setConnectionManager(manager).build();
    }
}
